
/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  poolint.integration;

//import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import pool.bean.IdBean;
import pool.bean.Master_table_Bean;
import control.RequestParameter;

import dbmanager.DBManager;
import dbmanager.GetIdName;


public class InsertMaster 
{

	/*private String integrateObject = "SugarpoolObject";
	private String tablistObj = "tablistobj";*/
	private String recentTableObject = "";
	String process = "add";
	String tableObj = "";
	String fieldTable = "table";
	String fieldTableName = "tablename";
	String fieldTablist = "tablelist";
	String fieldList = "fieldlist";
	String database = "database";
	String field = "field";
	String column = "column";
	String property_details = "property_details";
	String connObjId;
	
	//DBManager integratedDB;
	//Connection conn;
	GetIdName gin ;
	Hashtable<Object, Object> fieldHash = new Hashtable<Object, Object>();
	Hashtable<Object, Object> poolHash = new Hashtable<Object, Object>();
	Hashtable<Object, Object> ModuleHash = new Hashtable<Object, Object>();
	
	Vector<Object> propertyVect = new Vector<Object>();
	
	public InsertMaster() 
	{
		gin = new GetIdName();
	}
	
	public void setTableObj(String tableObj) 
	{
		this.tableObj = tableObj;		
	}
	
	public void setRecentTableObject(String recentTableObject) 
	{
		this.recentTableObject = recentTableObject;
	}
	/*public QueryProcessor(String integrateObject, String tablistObj)
	{
		this.integrateObject = integrateObject;
		this.tablistObj = tablistObj;
	}*/
	
	
	
	public void generateProperty() 
	{
		generateModuleHash();
		generatePoolHash();
		/**It will fetch the value from pool hash and append the column values in field hash.*/		
		Enumeration<Object> poolIte = poolHash.keys();
		while(poolIte.hasMoreElements())
		{
			String key=null;
			try 
			{
				key = poolIte.nextElement().toString();
				if(ModuleHash.containsKey(key))
				{
					String value = poolHash.get(key).toString();
					fieldHash.put(key, value);
				}
			} catch (Exception e) {
			}
		}
	}
	
	
	
	public void generateModuleHash()
	{
		/*String integrateObjId = gin.getId(integrateObject);
		String tablistObjId = gin.getId(tablistObj);
		
		ResultSet rsObject = dbsql.getSelect("SELECT pid, pv, vt FROM property_details WHERE mid = " + integrateObjId);*/
		
		/**Setting parameters for getting connection object.**/
		//String tableObjId = gin.getId(tableObj);
		
		
		/**Setting parameters for getting field list from table name.*/
		String fieldId = gin.getId(field);
		String columnId = gin.getId(column);
		String fieldListId = gin.getId(fieldList);
		
		String query = "SELECT DISTINCT d6.id,d6.mid, d6.pid, d6.pv, d6.vt FROM " + property_details + " d3 JOIN (" + property_details + " d4 JOIN (" + property_details + " d5 JOIN " + property_details;
		query = query + " d6 ON (d6.mid = d5.pv)) ON (d5.mid = d4.pv)) ON (d3.mid = d4.mid) ";
		query = query + "WHERE d3.mid = " + tableObj + " AND ";
		query = query + "d4.pid = " + fieldListId + " AND d5.pid = " + fieldId + " AND (d6.pid = " + fieldId +" OR d6.pid = " + columnId + ") order by d6.mid, d6.pid";
		
		System.out.println(" Query : " + query);
		ResultSet rsField = DBManager.getSelect(query);
		
		try 
		{
			while(rsField.next())
			{
				String mid1 = rsField.getString(2);
				String  poolDefinition = gin.getItem(rsField.getString("pv")).toLowerCase();
				rsField.next();
				String mid2 = rsField.getString(2);
				if(!mid1.equals(mid2))
					continue;
				String tableDefinition= gin.getItem(rsField.getString("pv")).toLowerCase();
				
				if(rsField.getString("pid").equals(columnId))
					ModuleHash.put(poolDefinition,tableDefinition);
				else
					ModuleHash.put(tableDefinition,poolDefinition);
			}
			rsField.close();
		}
		catch (Exception e) 
		{
			System.out.println("Exception::Integration:: PoolConnection.java, while fetching Fields and Columns ");
			e.printStackTrace();
		}
	}
	
	
	/**Getting recent object values from pool table.*/
	public void generatePoolHash()
	{
		try
		{
			ResultSet rsPoolValue = DBManager.getSelect("SELECT mid, pid, pv, vt FROM " + property_details + " WHERE mid = " + recentTableObject);
			while(rsPoolValue.next())
			{
				String pid = gin.getItem(rsPoolValue.getString("pid")).toLowerCase();
				String strPvVt = rsPoolValue.getString("pv"); // It will stores the value of PV or VT.
				
				if(strPvVt.equalsIgnoreCase("0"))
				{
					strPvVt = rsPoolValue.getString("vt");
				}
				else
				{
					strPvVt = gin.getItem(strPvVt);
				}
				poolHash.put(pid, strPvVt);
			}
			rsPoolValue.close();
		}
		catch (Exception e) 
		{
			System.out.println("Exception::Integration:: PoolConnection.java, while fetching Fields Values from POOL ");
			e.printStackTrace();
		}
	}
	
	
	
	public Vector<Object> getPropertyVector()
	{
		boolean FLAG = false;
		Enumeration<Object> poolIte = fieldHash.keys();
		while(poolIte.hasMoreElements())
		{
			String key = poolIte.nextElement().toString();
			String value = fieldHash.get(key).toString();
			Hashtable<Object, Object> hash = new Hashtable<Object, Object>();
			hash.put("pid", key);
			hash.put("pv", value);
			propertyVect.add(hash);
			FLAG = true;
		}
		if(FLAG)
		{
			Hashtable<Object, Object> hash = new Hashtable<Object, Object>();
			hash.put("pid", "type");
			hash.put("pv", gin.getItem(tableObj));
			propertyVect.add(hash);
		}
		return propertyVect;
	}
	
	
	
	public String insertMaster()
	{
		if(propertyVect.size()!=0)
		{
			RequestParameter rqp = new RequestParameter();
			rqp.setUsername("+911234567891");
			rqp.setPassword("891");
			rqp.setProcess(process);
			rqp.setVersion("11");
			rqp.setMessage("");
			rqp.setRequest("master_table");
			rqp.setEvent(false);
			IdBean idObj = new IdBean();
			idObj.setTable("master_table");
			idObj.execute();
			String id = idObj.getId();
			
			/** It will insert into M & PL of the POOLDB. **/
			String master = gin.getItem(tableObj)+ "_" + id;
			Master_table_Bean mtb = new Master_table_Bean();
			mtb.setReqParam(rqp);
			mtb.setNewMasterObject(master);
			getPropertyVector();
			mtb.setPropertyVector(propertyVect);
			mtb.insert();
			return master;
		}
		return null;
	}
	
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) 
	{
		InsertMaster qrypro = new InsertMaster();
		qrypro.setRecentTableObject("8458");
		qrypro.setTableObj("8405");
		qrypro.generateProperty();
		qrypro.setFields(new Hashtable<Object, Object>());
	}

	
	
	public void setFields(Hashtable<Object, Object> fieldHash2) 
	{
		fieldHash.putAll(fieldHash2);
	}
	
	
	public void setPoolHash(Hashtable<Object, Object> poolHash2) 
	{
		poolHash.putAll(poolHash2);
	}
	
	
	public void setModuleHash(Hashtable<Object, Object> moduleHash2) 
	{
		ModuleHash.putAll(moduleHash2);
	}
	
	
	public Hashtable<Object, Object> getModuleHash() {
		return ModuleHash;
	}
	
	
	public Hashtable<Object, Object> getPoolHash() {
		return poolHash;
	}
	
	
	public Hashtable<Object, Object> getFieldHash() {
		return fieldHash;
	}
	
	
}